package com.d3works.apps.maintenance.web;

import com.d3works.apps.maintenance.db.MaintenanceRequest;
import com.d3works.apps.maintenance.db.repo.MaintenanceRequestRepository;
import com.d3works.apps.maintenance.service.MaintenanceRequestService;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.google.inject.Inject;

public class MaintenanceRequestController {

  @Inject private MaintenanceRequestRepository maintenanceRequestRepo;

  @Inject private MaintenanceRequestService maintenanceRequestService;

  public void start(ActionRequest request, ActionResponse response) {

    MaintenanceRequest maintenanceRequest = request.getContext().asType(MaintenanceRequest.class);

    if (maintenanceRequest.getId() != null) {
      maintenanceRequest = maintenanceRequestRepo.find(maintenanceRequest.getId());
      maintenanceRequestService.start(maintenanceRequest);
      response.setReload(true);
    }
  }

  public void complete(ActionRequest request, ActionResponse response) {

    MaintenanceRequest maintenanceRequest = request.getContext().asType(MaintenanceRequest.class);

    if (maintenanceRequest.getId() != null) {
      maintenanceRequest = maintenanceRequestRepo.find(maintenanceRequest.getId());
      maintenanceRequestService.complete(maintenanceRequest);
      response.setReload(true);
    }
  }

  public void cancel(ActionRequest request, ActionResponse response) {

    MaintenanceRequest maintenanceRequest = request.getContext().asType(MaintenanceRequest.class);

    if (maintenanceRequest.getId() != null) {
      maintenanceRequest = maintenanceRequestRepo.find(maintenanceRequest.getId());
      maintenanceRequestService.cancel(maintenanceRequest);
      response.setReload(true);
    }
  }

  public void replan(ActionRequest request, ActionResponse response) {

    MaintenanceRequest maintenanceRequest = request.getContext().asType(MaintenanceRequest.class);

    if (maintenanceRequest.getId() != null) {
      maintenanceRequest = maintenanceRequestRepo.find(maintenanceRequest.getId());
      maintenanceRequestService.replan(maintenanceRequest);
      response.setReload(true);
    }
  }
}
